package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Sring和Interger之间的转换
 * @author LiangRuiJiang
 * @since 2022/06/06  16:34
 */
@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntergerArrayTypeHandler implements TypeHandler<Integer[]> {

    ObjectMapper objectMapper = new ObjectMapper();

    //输入映射过程
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, Integer[] integers, JdbcType jdbcType) throws SQLException {

        String value = null;
        try {
            value = objectMapper.writeValueAsString(integers);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        preparedStatement.setString(index,value);
    }

    //输出映射
    @Override
    public Integer[] getResult(ResultSet resultSet, String column) throws SQLException {
        //根据列名获得对应的值
        String result = resultSet.getString(column);
        return this.transfer(result);
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int index) throws SQLException {
        //根据下标获取对应的值
        String result = resultSet.getString(index);
        return this.transfer(result);
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        // 根据序号获取对应的值
        String result = callableStatement.getString(i);
        return this.transfer(result);
    }

    private Integer[] transfer(String result){
        Integer[] integers = new Integer[0];
        try {
            integers = objectMapper.readValue(result, Integer[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return integers;
    }
}
